import cv2
from picamera2 import Picamera2
from datetime import datetime
import time

def main():
    picam2 = Picamera2()
    config = picam2.create_still_configuration(
            main={"size": (640, 480)},
            controls={"FrameRate": 30}
        )
    picam2.configure(config)
    picam2.start()
    print(f"Camera started at {datetime.now()}")

    fps = 30  # 读取出来是30FPS，但实际是15FPS，所以这里强制设置为15FPS
    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    out = cv2.VideoWriter("output.mp4", fourcc, fps, (640, 480))
    print(f"width: {640}, height: {480}, fps: {fps}")

    start_time = time.time()
    print("Start recording...")

    while True:
        frame = picam2.capture_array()
        if frame is None:
            out.write(frame)

        # 检查是否录制超过 10 秒
        if time.time() - start_time > 10:
            print("Finished recording")
            break

        # 可选：按下 q 提前退出
        if cv2.waitKey(1) & 0xFF == ord("q"):
            print("Early exit")
            break
        
    picam2.stop()
    out.release()
    print("Camera stopped and video saved.")

if __name__ == "__main__":
    main()